//
//  CLClickBtnOtherViewController.m
//  CareLink
//
//  Created by w on 16/8/18.
//  Copyright © 2016年 Seven Team. All rights reserved.

#import "CLAEViewController.h"
#import "CLClickBtnOtherViewController.h"
#import "CLSettingPWViewController.h"
#import "SVProgressHUD.h"
#import <SMS_SDK/SMSSDK.h>
#import "CLHomeViewController.h"
@interface CLClickBtnOtherViewController () {
    //文本视图
    UIView* bgView;
    //手机号
    UITextField* phone;
    //验证码内容
    UITextField* code;
    //推荐
    UITextField* reCommand;
    //navBar
    UINavigationBar* customNavigationBar;
    //获取验证码btn
    UIButton* yButton;
}

@property (nonatomic, copy) NSString* oUserPhoneNum;
//计数
@property (assign, nonatomic) NSInteger timeCount;
//验证时间
@property (strong, nonatomic) NSTimer* timer;
//验证码
@property (copy, nonatomic) NSString* smsId;

@property (nonatomic, copy) NSString* keyStr;
@end
/**
 *  手机登录注册1/3
 */
@implementation CLClickBtnOtherViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:240 / 255.0f green:240 / 255.0f blue:240 / 255.0f alpha:1];
    //   self.title = @"注册";
    //显示navbar内容同时设置 navBar 显示
    //    self.navigationController.navigationBarHidden = NO;
    //    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    self.view.backgroundColor = [UIColor colorWithRed:240 / 255.0f green:240 / 255.0f blue:240 / 255.0f alpha:1];
    UIBarButtonItem* addBtn = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(clickaddBtn)];
    [addBtn setImage:[UIImage imageNamed:@"goback_back_orange_on"]]; //箭头图标
    [addBtn setImageInsets:UIEdgeInsetsMake(0, -15, 0, 15)];
    addBtn.tintColor = [UIColor colorWithRed:248 / 255.0f green:114 / 255.0f blue:34 / 255.0f alpha:1];
    //    [self.navigationItem setLeftBarButtonItem:addBtn];
    [self creatTextFields];
}
#pragma mark控制器的跳转(主登录控制器)
- (void)clickaddBtn
{
    //    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController pushViewController:[[CLAEViewController alloc] init] animated:YES];
}
#pragma mark 创建主页的账号密码登录文本
- (void)creatTextFields
{
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(25, 36, self.view.frame.size.width - 90, 30)];
    label.text = @"请输入您的手机号码";
    label.textColor = [UIColor grayColor];
    label.textAlignment = UITextAlignmentLeft;
    //字体大小font
    label.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:label];

    CGRect frame = [UIScreen mainScreen].bounds;
    bgView = [[UIView alloc] initWithFrame:CGRectMake(10, 60, frame.size.width - 20, 150)];
    bgView.layer.cornerRadius = 3.0;
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];

    //设置登录的手机号和密码信息
    phone = [self createTextFielfFrame:CGRectMake(100, 10, 210, 30) font:[UIFont systemFontOfSize:14] placeholder:@"请输入11位手机号"];

    // phone.secureTextEntry = YES;
    phone.keyboardType = UIKeyboardTypeNumberPad;
    phone.clearButtonMode = UITextFieldViewModeWhileEditing;
    code = [self createTextFielfFrame:CGRectMake(100, 60, 90, 30) font:[UIFont systemFontOfSize:14] placeholder:@"四位数字"];
    code.clearButtonMode = UITextFieldViewModeWhileEditing;
    code.secureTextEntry = YES;
    code.keyboardType = UIKeyboardTypeNumberPad;

    reCommand = [self createTextFielfFrame:CGRectMake(100, 110, 210, 30) font:[UIFont systemFontOfSize:14] placeholder:@"请输入推荐人号码(选填)"];
    reCommand.clearButtonMode = UITextFieldViewModeWhileEditing;
    reCommand.secureTextEntry = YES;
    reCommand.keyboardType = UIKeyboardTypeNumberPad;

    UIImageView* userImageView = [self createImageViewFrame:CGRectMake(23, 15, 16, 16) imageName:@"注册-手机号" color:nil];
    UIImageView* pwdImageView = [self createImageViewFrame:CGRectMake(20, 60, 25, 25) imageName:@"mm_normal" color:nil];
    UIImageView* pwdImageView2 = [self createImageViewFrame:CGRectMake(20, 110, 25, 25) imageName:@"share_copyLink" color:nil];

#pragma mark 用户协议
    //添加阅读同意使用勾选
    UIButton* chooseBTN = [[UIButton alloc] init];
    chooseBTN = [[UIButton alloc] initWithFrame:CGRectMake(-19, 210, 80, 25)];
    [chooseBTN setImage:[UIImage imageNamed:@"zc_select"] forState:UIControlStateNormal];
    [chooseBTN setImage:[UIImage imageNamed:@"zc_unselect"] forState:UIControlStateSelected];
    [chooseBTN addTarget:self action:@selector(chooseBTN:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:chooseBTN];

    UILabel* idLAB = [[UILabel alloc] init];
    idLAB = [[UILabel alloc] initWithFrame:CGRectMake(27, 210, 85, 25)];
    idLAB.text = @"我已阅读并同意";
    idLAB.textColor = [UIColor colorWithHex:0X0073dd];
    idLAB.font = [UIFont systemFontOfSize:12.0];
    idLAB.numberOfLines = 1;
    [self.view addSubview:idLAB];

    UIButton* id2BTN = [[UIButton alloc] init];
    id2BTN = [[UIButton alloc] initWithFrame:CGRectMake(bgView.frame.size.width - 245, 208, 100, 80)];
    [id2BTN setTitle:@"<<查看使用条款和隐私政策>>" forState:UIControlStateNormal];
    [id2BTN setTitleColor:[UIColor colorWithHex:0X014b82] forState:UIControlStateNormal];
    id2BTN.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [id2BTN sizeToFit];
    [self.view addSubview:id2BTN];
    [id2BTN addTarget:self action:@selector(id2BTNDidClick:) forControlEvents:UIControlEventTouchUpInside];

    //获取验证码btn
    yButton = [[UIButton alloc] initWithFrame:CGRectMake(bgView.frame.size.width - 105, 62, 100, 30)];
    //yButton.layer.cornerRadius=3.0f;
    //yzButton.backgroundColor=[UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1];
    [yButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [yButton setTitleColor:[UIColor colorWithRed:8 / 255.0 green:65 / 255.0 blue:130 / 255.0 alpha:0.8] forState:UIControlStateNormal];
    yButton.font = [UIFont systemFontOfSize:13];
    [yButton addTarget:self action:@selector(GetValidCode:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:yButton];

    //分隔线
    UIImageView* line1 = [self createImageViewFrame:CGRectMake(20, 50, bgView.frame.size.width - 40, 1) imageName:nil color:[UIColor colorWithRed:180 / 255.0f green:180 / 255.0f blue:180 / 255.0f alpha:.3]];
    //分隔线2
    UIImageView* line2 = [self createImageViewFrame:CGRectMake(20, 102, bgView.frame.size.width - 40, 1) imageName:nil color:[UIColor colorWithRed:180 / 255.0f green:180 / 255.0f blue:180 / 255.0f alpha:.3]];
    //下一步按钮
    UIButton* landBtn = [self createButtonFrame:CGRectMake(10, bgView.frame.size.height + bgView.frame.origin.y + 50, self.view.frame.size.width - 20, 37) backImageName:nil title:@"下一步" titleColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:17] target:self action:@selector(Next)];
    landBtn.backgroundColor = [UIColor colorWithRed:8 / 255.0 green:65 / 255.0 blue:130 / 255.0 alpha:0.8];
    landBtn.layer.cornerRadius = 5.0f;

    [bgView addSubview:phone];
    [bgView addSubview:code];
    [bgView addSubview:reCommand];

    //添加手机号 验证码 分割线
    [bgView addSubview:userImageView];
    [bgView addSubview:pwdImageView];
    [bgView addSubview:pwdImageView2];
    [bgView addSubview:line1];
    [bgView addSubview:line2];
    [self.view addSubview:landBtn];
}
#pragma mark 获取验证码和验证码的读取时间
- (void)GetValidCode:(UIButton*)sender
{

    if ([phone.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"亲,请输入手机号码"];
        return;
    }
    else if (phone.text.length < 11) {
        [SVProgressHUD showInfoWithStatus:@"您输入的手机号码格式不正确"];
        return;
    }
    //这里加上验证码提示功能
    _oUserPhoneNum = phone.text;
    //用户交互
    sender.userInteractionEnabled = YES;
    //验证码计时
    self.timeCount = 60;
    //__weak CLForgetPWViewController *weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reduceTime:) userInfo:sender repeats:YES];
    //短信验证功能
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self->phone.text zone:@"86" customIdentifier:nil result:^(NSError* error) {
        if (!error) {
            NSLog(@"成功");
            UIAlertController* alertView = [UIAlertController alertControllerWithTitle:@"" message:@"验证成功" preferredStyle:UIAlertControllerStyleAlert];
            //            [self presentViewController:alertView animated:YES completion:^{
            [NSThread sleepForTimeInterval:2.0];
        }
        else {
            NSLog(@"%@", error);
            [SVProgressHUD showInfoWithStatus:@"亲,验证码获取失败,请重新获取"];
        }
    }];
}
- (void)reduceTime:(NSTimer*)codeTimer
{
    self.timeCount--;
    if (self.timeCount == 0) {
        [yButton setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        [yButton setTitleColor:[UIColor colorWithRed:248 / 255.0f green:144 / 255.0f blue:34 / 255.0f alpha:1] forState:UIControlStateNormal];
        UIButton* info = codeTimer.userInfo;
        info.enabled = YES;
        yButton.userInteractionEnabled = YES;
        [self.timer invalidate];
    }
    else {
        NSString* str = [NSString stringWithFormat:@"%lu秒后重新获取", self.timeCount];
        [yButton setTitle:str forState:UIControlStateNormal];
        yButton.userInteractionEnabled = NO;
    }
}

#pragma mark -点击同意阅读
- (void)chooseBTN:(UIButton*)chooseBTN
{
    UIButton* btn = (UIButton*)chooseBTN;
    if (btn.isSelected == true) {
        btn.selected = false;
    }
    else if (btn.isSelected == false) {
        btn.selected = true;
    }
}

- (void)id2BTNDidClick:(UIButton*)id2BTN
{
    UIAlertController* ac = [UIAlertController alertControllerWithTitle:@"  <<使用条款和隐私政策>>  " message:@"快医在此特别提醒用户认真阅读、充分理解本《用户协议》（下称《协议》）--- 用户应认真阅读、充分理解本《协议》中各条款，包括免除或者限制英特沃克责任的免责条款及对用户的权利限制条款。请您审慎阅读并选择接受或不接受本《协议》（未成年人应在法定监护人陪同下阅读）。除非您接受本《协议》所有条款，否则您无权注册、登录或使用本协议所涉相关服务。您的注册、登录、使用等行为将视为对本《协议》的接受，并同意接受本《协议》各项条款的约束。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* confirm = [UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:^(UIAlertAction* _Nonnull action){

    }];
    [ac addAction:confirm];
    [self presentViewController:ac animated:true completion:^{
    }];
}
//关闭第一响应
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{

    [phone resignFirstResponder];
}
- (UITextField*)createTextFielfFrame:(CGRect)frame font:(UIFont*)font placeholder:(NSString*)placeholder
{
    UITextField* textField = [[UITextField alloc] initWithFrame:frame];

    textField.font = font;

    textField.textColor = [UIColor grayColor];

    textField.borderStyle = UITextBorderStyleNone;

    textField.placeholder = placeholder;

    return textField;
}

- (UIImageView*)createImageViewFrame:(CGRect)frame imageName:(NSString*)imageName color:(UIColor*)color
{
    UIImageView* imageView = [[UIImageView alloc] initWithFrame:frame];

    if (imageName) {
        imageView.image = [UIImage imageNamed:imageName];
    }
    if (color) {
        imageView.backgroundColor = color;
    }
    return imageView;
}

- (UIButton*)createButtonFrame:(CGRect)frame backImageName:(NSString*)imageName title:(NSString*)title titleColor:(UIColor*)color font:(UIFont*)font target:(id)target action:(SEL)action
{
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    if (imageName) {
        [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }

    if (font) {
        btn.titleLabel.font = font;
    }

    if (title) {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    if (color) {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
    if (target && action) {
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}

//实现验证码功能
- (void)Next
{
    if ([phone.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"亲,请输入注册手机号码"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    else if (phone.text.length < 11) {
        [SVProgressHUD showInfoWithStatus:@"您输入的手机号码格式不正确"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });

        return;
    }
    else if ([code.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"亲,请输入验证码"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });

        return;
    }

    self.keyStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"tel"];
    [SMSSDK commitVerificationCode:self->code.text phoneNumber:phone.text zone:@"86" result:^(NSError* error) {
        NSLog(@"%@---%@", self->code.text, self.keyStr);
        if (!error) {
            switch (self.number) {
                case 0: {
                    //保存手机号，即用户名,
                    [[NSUserDefaults standardUserDefaults] setObject:phone.text forKey:KUserName];
                    CLSettingPWViewController* vc = [[CLSettingPWViewController alloc] init];
                    vc.number = 0;
                    //输入验证码成功跳转到设置密码界面
                    [self.navigationController pushViewController:vc animated:YES];
                    
                } break;
                case 1: {
                    [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:KisLoad];
                    CLHomeViewController* vc = [[CLHomeViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                    
                    [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                    });
                    
                } break;
                case 2: {
                    //保存手机号，即用户名,
                    [[NSUserDefaults standardUserDefaults] setObject:phone.text forKey:KUserName];
                    CLSettingPWViewController* vc = [[CLSettingPWViewController alloc] init];
                    vc.number = 2;
                    //输入验证码成功跳转到设置密码界面
                    [self.navigationController pushViewController:vc animated:YES];
                    
                } break;
                default:
                    break;
            }
        }
        else {
            NSLog(@"%@", error);
            [SVProgressHUD showInfoWithStatus:@"亲,您输入的验证码不正确,请重新获取"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
    }];
}
@end
